package com.lua;

import com.config.Config;
import com.helper.Debug;
import com.lua.cache.LuaCache;
import com.nioserver.io.WorkPool;
import com.nioserver.io.task.LuaEvent;
import com.nioserver.lib.LuaLoadInfo;
import com.nioserver.lib.LuaObj;
import net.sf.json.JSONObject;
import org.junit.Test;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.compiler.LuaC;
import org.luaj.vm2.lib.jse.JsePlatform;

import java.io.IOException;
import java.util.HashMap;

public class CallLua {


    Globals globals;

    public static CallLua Instance;
    public static CallLua getInstance(){

        if(Instance == null){

            Instance = new CallLua();

        }

        return Instance;

    }
    public LuaObj launch(String name,String file){
        LuaLoadInfo info = load(file);
        LuaValue val = info.val;
        if(val == null){
            return null;
        }
        val = val.call();

        LuaValue start = val.get("start");
        if(start!= null){
            start.call();
        }

        int address = LuaCache.insertToList(val);
        String uuid = LuaCache.insertMap(val);
        LuaObj obj = new LuaObj(name,val,address,info.name);
        return obj;

    }

    public String call(int pos,String function,String params){

        if(LuaCache.getFromList(pos).isnil()){

            Debug.log("have not the service");
            return "";
        }
//
        if(LuaCache.getFromList(pos).get(function).isnil()){
            Debug.log("have not the function");
            return "";
        }
        LuaValue val = LuaCache.getFromList(pos).get(function).call(params);

        JSONObject jsonObject = JSONObject.fromObject(val.tojstring());
        return jsonObject.toString();
    }
    public void asyncCall(int pos,String function,String params){
        WorkPool.getInstance().submitTask(new LuaEvent(pos,function,params));

    }
    public LuaObj launch(String file){

        LuaLoadInfo info = load(file);
        LuaValue val = info.val;
        if(val == null){
            return null;
        }
        val = val.call();
        if(!val.isnil()){
            LuaValue start = val.get("start");
            if(!start.isnil()){
                start.call();
            }
        }
        int address = LuaCache.insertToList(val);
        String uuid = LuaCache.insertMap(val);
        LuaObj obj = new LuaObj(uuid,val,address,info.name);
        return obj;
    }

    public CallLua(){

        globals= JsePlatform.standardGlobals();
    }




    LuaLoadInfo load(String file){
        LuaLoadInfo info = new LuaLoadInfo();
        info.path = Config.LuaPath +"/"+file+".lua";
        info.name = file;

        LuaValue val = globals.loadFile(Config.LuaPath +"/"+file+".lua");
        info.val = val;
        return info;
    }

}


